{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import glob\n",
    "import os.path\n",
    "import random\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow.python.platform import gfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 模型和样本路径的设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "BOTTLENECK_TENSOR_SIZE = 2048\n",
    "BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'\n",
    "JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'\n",
    "\n",
    "\n",
    "# 下载训练好的模型，解压放到../datasets/inception_dec_2015目录\n",
    "# wget https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip\n",
    "\n",
    "MODEL_DIR = '../datasets/inception_dec_2015'\n",
    "MODEL_FILE= 'tensorflow_inception_graph.pb'\n",
    "\n",
    "# 下载flowers测试数据，解压放到../datasets/flower_photos目录\n",
    "# wget http://download.tensorflow.org/example_images/flower_photos.tgz\n",
    "# 每个子文件夹存放了对应类别的图片\n",
    "INPUT_DATA = '../datasets/flower_photos'\n",
    "\n",
    "# 因为一个训练数据集会被使用多次，所以可以将演示图像通过inception-v3模型\n",
    "# 得到的特征向量保存在文件中，免去重复计算\n",
    "CACHE_DIR = '../datasets/bottleneck'\n",
    "\n",
    "# 验证的数据百分比\n",
    "VALIDATION_PERCENTAGE = 10\n",
    "# 测试的数据百分比\n",
    "TEST_PERCENTAGE = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 神经网络参数的设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 神经网络设置\n",
    "LEARNING_RATE = 0.01\n",
    "STEPS = 4000\n",
    "BATCH = 100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 把样本中所有的图片列表并按训练、验证、测试数据分开"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def create_image_lists(testing_percentage, validation_percentage):\n",
    "    result = {}\n",
    "    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]\n",
    "    is_root_dir = True\n",
    "    for sub_dir in sub_dirs:\n",
    "        if is_root_dir:\n",
    "            is_root_dir = False\n",
    "            continue\n",
    "\n",
    "        extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']\n",
    "\n",
    "        file_list = []\n",
    "        dir_name = os.path.basename(sub_dir)\n",
    "        for extension in extensions:\n",
    "            file_glob = os.path.join(INPUT_DATA, dir_name, '*.' + extension)\n",
    "            file_list.extend(glob.glob(file_glob))\n",
    "        if not file_list: continue\n",
    "\n",
    "        label_name = dir_name.lower()\n",
    "        \n",
    "        # 初始化\n",
    "        training_images = []\n",
    "        testing_images = []\n",
    "        validation_images = []\n",
    "        for file_name in file_list:\n",
    "            base_name = os.path.basename(file_name)\n",
    "            \n",
    "            # 随机划分数据\n",
    "            chance = np.random.randint(100)\n",
    "            if chance < validation_percentage:\n",
    "                validation_images.append(base_name)\n",
    "            elif chance < (testing_percentage + validation_percentage):\n",
    "                testing_images.append(base_name)\n",
    "            else:\n",
    "                training_images.append(base_name)\n",
    "\n",
    "        result[label_name] = {\n",
    "            'dir': dir_name,\n",
    "            'training': training_images,\n",
    "            'testing': testing_images,\n",
    "            'validation': validation_images,\n",
    "            }\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 定义函数通过类别名称、所属数据集和图片编号获取一张图片的地址。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_image_path(image_lists, image_dir, label_name, index, category):\n",
    "    label_lists = image_lists[label_name]\n",
    "    category_list = label_lists[category]\n",
    "    mod_index = index % len(category_list)\n",
    "    base_name = category_list[mod_index]\n",
    "    sub_dir = label_lists['dir']\n",
    "    full_path = os.path.join(image_dir, sub_dir, base_name)\n",
    "    return full_path"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5. 定义函数获取Inception-v3模型处理之后的特征向量的文件地址。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_bottleneck_path(image_lists, label_name, index, category):\n",
    "    return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 6. 定义函数使用加载的训练好的Inception-v3模型处理一张图片，得到这个图片的特征向量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):\n",
    "\n",
    "    bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})\n",
    "\n",
    "    bottleneck_values = np.squeeze(bottleneck_values)\n",
    "    return bottleneck_values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 7. 定义函数会先试图寻找已经计算且保存下来的特征向量，如果找不到则先计算这个特征向量，然后保存到文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):\n",
    "    label_lists = image_lists[label_name]\n",
    "    sub_dir = label_lists['dir']\n",
    "    sub_dir_path = os.path.join(CACHE_DIR, sub_dir)\n",
    "    if not os.path.exists(sub_dir_path): os.makedirs(sub_dir_path)\n",
    "    bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)\n",
    "    if not os.path.exists(bottleneck_path):\n",
    "\n",
    "        image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)\n",
    "\n",
    "        image_data = gfile.FastGFile(image_path, 'rb').read()\n",
    "\n",
    "        bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)\n",
    "\n",
    "        bottleneck_string = ','.join(str(x) for x in bottleneck_values)\n",
    "        with open(bottleneck_path, 'w') as bottleneck_file:\n",
    "            bottleneck_file.write(bottleneck_string)\n",
    "    else:\n",
    "\n",
    "        with open(bottleneck_path, 'r') as bottleneck_file:\n",
    "            bottleneck_string = bottleneck_file.read()\n",
    "        bottleneck_values = [float(x) for x in bottleneck_string.split(',')]\n",
    "\n",
    "    return bottleneck_values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 8. 这个函数随机获取一个batch的图片作为训练数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, jpeg_data_tensor, bottleneck_tensor):\n",
    "    bottlenecks = []\n",
    "    ground_truths = []\n",
    "    for _ in range(how_many):\n",
    "        label_index = random.randrange(n_classes)\n",
    "        label_name = list(image_lists.keys())[label_index]\n",
    "        image_index = random.randrange(65536)\n",
    "        bottleneck = get_or_create_bottleneck(\n",
    "            sess, image_lists, label_name, image_index, category, jpeg_data_tensor, bottleneck_tensor)\n",
    "        ground_truth = np.zeros(n_classes, dtype=np.float32)\n",
    "        ground_truth[label_index] = 1.0\n",
    "        bottlenecks.append(bottleneck)\n",
    "        ground_truths.append(ground_truth)\n",
    "\n",
    "    return bottlenecks, ground_truths"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 9. 这个函数获取全部的测试数据，并计算正确率。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):\n",
    "    bottlenecks = []\n",
    "    ground_truths = []\n",
    "    label_name_list = list(image_lists.keys())\n",
    "    for label_index, label_name in enumerate(label_name_list):\n",
    "        category = 'testing'\n",
    "        for index, unused_base_name in enumerate(image_lists[label_name][category]):\n",
    "            bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,jpeg_data_tensor, bottleneck_tensor)\n",
    "            ground_truth = np.zeros(n_classes, dtype=np.float32)\n",
    "            ground_truth[label_index] = 1.0\n",
    "            bottlenecks.append(bottleneck)\n",
    "            ground_truths.append(ground_truth)\n",
    "    return bottlenecks, ground_truths"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 10. 定义主函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 0: Validation accuracy on random sampled 100 examples = 34.0%\n",
      "Step 100: Validation accuracy on random sampled 100 examples = 85.0%\n",
      "Step 200: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 300: Validation accuracy on random sampled 100 examples = 95.0%\n",
      "Step 400: Validation accuracy on random sampled 100 examples = 83.0%\n",
      "Step 500: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 600: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 700: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 800: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 900: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 1000: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 1100: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 1200: Validation accuracy on random sampled 100 examples = 87.0%\n",
      "Step 1300: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 1400: Validation accuracy on random sampled 100 examples = 85.0%\n",
      "Step 1500: Validation accuracy on random sampled 100 examples = 93.0%\n",
      "Step 1600: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 1700: Validation accuracy on random sampled 100 examples = 84.0%\n",
      "Step 1800: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 1900: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 2000: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 2100: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 2200: Validation accuracy on random sampled 100 examples = 85.0%\n",
      "Step 2300: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 2400: Validation accuracy on random sampled 100 examples = 93.0%\n",
      "Step 2500: Validation accuracy on random sampled 100 examples = 94.0%\n",
      "Step 2600: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 2700: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 2800: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 2900: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 3000: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 3100: Validation accuracy on random sampled 100 examples = 97.0%\n",
      "Step 3200: Validation accuracy on random sampled 100 examples = 93.0%\n",
      "Step 3300: Validation accuracy on random sampled 100 examples = 94.0%\n",
      "Step 3400: Validation accuracy on random sampled 100 examples = 87.0%\n",
      "Step 3500: Validation accuracy on random sampled 100 examples = 94.0%\n",
      "Step 3600: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 3700: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 3800: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 3900: Validation accuracy on random sampled 100 examples = 95.0%\n",
      "Step 3999: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Final test accuracy = 93.6%\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)\n",
    "    n_classes = len(image_lists.keys())\n",
    "    \n",
    "    # 读取已经训练好的Inception-v3模型。\n",
    "    with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "    bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(\n",
    "        graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])\n",
    "\n",
    "    # 定义新的神经网络输入\n",
    "    bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE], name='BottleneckInputPlaceholder')\n",
    "    ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')\n",
    "    \n",
    "    # 定义一层全链接层\n",
    "    with tf.name_scope('final_training_ops'):\n",
    "        weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))\n",
    "        biases = tf.Variable(tf.zeros([n_classes]))\n",
    "        logits = tf.matmul(bottleneck_input, weights) + biases\n",
    "        final_tensor = tf.nn.softmax(logits)\n",
    "        \n",
    "    # 定义交叉熵损失函数。\n",
    "    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input)\n",
    "    cross_entropy_mean = tf.reduce_mean(cross_entropy)\n",
    "    train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)\n",
    "    \n",
    "    # 计算正确率。\n",
    "    with tf.name_scope('evaluation'):\n",
    "        correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))\n",
    "        evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "    with tf.Session() as sess:\n",
    "        init = tf.global_variables_initializer()\n",
    "        sess.run(init)\n",
    "        # 训练过程。\n",
    "        for i in range(STEPS):\n",
    " \n",
    "            train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(\n",
    "                sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)\n",
    "            sess.run(train_step, feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth})\n",
    "\n",
    "            if i % 100 == 0 or i + 1 == STEPS:\n",
    "                validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(\n",
    "                    sess, n_classes, image_lists, BATCH, 'validation', jpeg_data_tensor, bottleneck_tensor)\n",
    "                validation_accuracy = sess.run(evaluation_step, feed_dict={\n",
    "                    bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth})\n",
    "                print('Step %d: Validation accuracy on random sampled %d examples = %.1f%%' %\n",
    "                    (i, BATCH, validation_accuracy * 100))\n",
    "            \n",
    "        # 在最后的测试数据上测试正确率。\n",
    "        test_bottlenecks, test_ground_truth = get_test_bottlenecks(\n",
    "            sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor)\n",
    "        test_accuracy = sess.run(evaluation_step, feed_dict={\n",
    "            bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth})\n",
    "        print('Final test accuracy = %.1f%%' % (test_accuracy * 100))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
